package net.xiaosaguo.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * description: 自定义注解校验器，需指定注解和校验类型
 *
 * @author xiaosaguo
 * @date 2020/06/10
 */
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {

    private Set<Integer> set = new HashSet<>();

    /**
     * description: 初始化方法
     *
     * @param constraintAnnotation 约束注解的实例
     * @author xiaosaguo
     * @date 2020/06/10 20:45
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] vals = constraintAnnotation.vals();
        for (int val : vals) {
            set.add(val);
        }
    }

    /**
     * description: 是否校验成功
     *
     * @param value   被校验的值
     * @param context 上下文环境信息
     * @return boolean 校验结果
     * @author xiaosaguo
     * @date 2020/06/10 20:47
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return set.contains(value);
    }
}
